#!/usr/bin/env python

import sys
import data
import pickle
import os.path
import logging
from sqlobject import *

logger = logging.getLogger('allconsumingdac')

class User(SQLObject):
    name = StringCol(alternateID=True)

class Consumable(SQLObject):
    user = ForeignKey('User')
    item = ForeignKey('Item')
    
#     consumed = False
#     tags = []
#     worthIt = None
#     numEntries = 0

class Item(SQLObject):
    number = StringCol()
    title = StringCol()

_inited = False

def _init():
    global _inited
    if _inited:
        return

    print '_initing'
    db_filename = os.path.abspath('data.db')

    needToCreate = not os.path.exists(db_filename)

    connection_string = 'sqlite:' + '/' + db_filename.replace(':', '|').replace('\\', '/')
    connection = connectionForURI(connection_string)
    sqlhub.processConnection = connection    

    if needToCreate:
        Consumable.createTable()
        Item.createTable()
        User.createTable()
        
        u = User(name='Hippopottoman')
        i = Item(number='123', title='The Tao of Pooh')
        print 'created', i
        c = Consumable(user=u, item=i)
        print 'created', c

    _inited = True
    
def getUserList():
    '''Get a list of users from the file store. Returned as a list of
    (lastUpdateTime, userName) tuples''' 
    _init()

    allUsers = User.select()
    for u in allUsers:
        print u

def getItemList():
    _init()
    '''Get a list of items from the file store. Returned as a list of
    (lastUpdateTime, itemNumber) tuples''' 

    pass

def getUserConsumables(userName):
    _init()
    u = User.byName(userName)
    print u
    pass

def saveUserConsumables(userName, consumables):
    # for now, assume it's the consumables for one user, and all
    # of that user's consumables
    pass

def saveItemUsers(itemNumber, users):
    _init()
    pass

def getItemUsers(itemNumber):
    _init()
    pass


def do_main():
    _init()
    
    c = Consumable.get(1)
    print c, c.user, c.item

    getUserList()
    getUserConsumables('Hippopottoman')
    
if __name__ == '__main__':
    do_main()
